package com.atguigu.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.yygh.cmn.listener.DictListener;
import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.enums.DictEnum;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;


@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService{
    @Autowired
    DictListener dictListener;

    @Cacheable(value = "dict")
    @Override
    public List<Dict> findChildData(long id) {
        QueryWrapper<Dict> wrapper=new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        List<Dict> list = baseMapper.selectList(wrapper);
        for (int i=0;i<list.size();i++){
            Dict dict = list.get(i);
            boolean children = isChildren(dict.getId());
            if (children){
                dict.setHasChildren(true);
            }
        }
        return list;
    }

    @Override
    public void exportData(HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName= URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition","attachment;filename="+ fileName + ".xlsx");
            List<Dict> list = baseMapper.selectList(null);
            List<DictEeVo> voList=new ArrayList<>();
            for (Dict dict : list) {
                DictEeVo dictEeVo=new DictEeVo();
                BeanUtils.copyProperties(dict,dictEeVo);
                voList.add(dictEeVo);
            }
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(voList);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,dictListener).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getNameByParentDictCodeAndValue(String parentDictCode, String value) {
        if (StringUtils.isEmpty(parentDictCode)) {
            QueryWrapper wrapper=new QueryWrapper();
            wrapper.eq("value", value);
            Dict dict = baseMapper.selectOne(wrapper);
            return dict.getName();
        } else {
            Dict parentDict = this.getDictByDictCode(parentDictCode);
            if (null!=parentDict){
                QueryWrapper<Dict> wrapper=new QueryWrapper();
                wrapper.eq("parent_id",parentDict.getId());
                wrapper.eq("value",value);
                Dict dict = baseMapper.selectOne(wrapper);
                return dict.getName();
            }
        }
        return null;
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        Dict dict = this.getDictByDictCode(dictCode);
        if (dict!=null){
            QueryWrapper<Dict> wrapper=new QueryWrapper();
            wrapper.eq("parent_id", dict.getId());
            List<Dict> list = baseMapper.selectList(wrapper);
            return list;
        }
        return null;
    }

    private Dict getDictByDictCode(String parentDictCode) {
        QueryWrapper<Dict> wrapper=new QueryWrapper();
        wrapper.eq("dict_code", parentDictCode);
        Dict dict = baseMapper.selectOne(wrapper);
        return dict;
    }

    private boolean isChildren(long id){
        QueryWrapper<Dict> wrapper=new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        Integer count = baseMapper.selectCount(wrapper);
        return count>0;
    }
}
